package com.fybspace.DataSource;

import com.fybspace.primary.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService(){
        return new UserDetailService();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
//                .antMatchers("/**").hasAnyRole("USER,ADMIN")//表示映射为/**的需要角色USER,ADMIN
//                .antMatchers("/**").access("hasRole('ADMIN')")//这两种写法都有效
//                .antMatchers("/", "/home")
//                .permitAll()//表示允许所有角色访问
                .anyRequest()
                .authenticated()//表示需要认证?
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .rememberMe()//勿忘我
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        //为登陆的数据库用户
        auth
                .userDetailsService(userDetailsService());

        //为内存里设定的帐号
        auth
            .inMemoryAuthentication()
                .withUser("root").password("123456").roles("USER");
    }

}